/**
 * User: alesj
 * Date: 18.3.2006
 * Time: 15:53:08
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.alesj.blade.util;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * @author <a href="mailto:ales.justin@genera-lynx.com">Ales Justin</a>
 */
public class Utils {

    public static void warnUser(String msgid, Object params[]) {
        warnUser(null, msgid, params);
    }

    public static void warnUser(String component, String msgid, Object params[]) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        ctx.addMessage(component, getMessage(msgid, params, FacesMessage.SEVERITY_ERROR));
    }

    // move somewhere else
    public static FacesMessage getMessage(String messageId,
                                          Object params[],
                                          FacesMessage.Severity severity) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        String bundleName = facesContext.getApplication().getMessageBundle();
        if (bundleName != null) {
            String summary = null;
            String detail = null;
            Locale locale = facesContext.getViewRoot().getLocale();
            ResourceBundle bundle = ResourceBundle.getBundle(bundleName,
                    locale,
                    Thread.currentThread().getContextClassLoader());
            try {
                summary = bundle.getString(messageId);
                detail = bundle.getString(messageId + "_detail");
            }
            catch (MissingResourceException e) {
                //ignore
            }

            if (summary != null) {
                MessageFormat mf = null;
                if (params != null) {
                    mf = new MessageFormat(summary, locale);
                    summary = mf.format(params, new StringBuffer(), null).toString();
                }
                if (detail != null && params != null) {
                    mf.applyPattern(detail);
                    detail = mf.format(params, new StringBuffer(), null).toString();
                }
                return (new FacesMessage(severity, summary, detail));
            }
        }
        return new FacesMessage(severity, "!! key " + messageId + " not found !!", null);
    }

}
